package com.jcl.cloud.services.crawler.brain.thread;

import com.jcl.cloud.services.crawler.brain.constant.TaskRecord;
import com.jcl.cloud.services.crawler.brain.service.RedisService;

import java.util.concurrent.ConcurrentHashMap;

public class TaskWatchThread implements Runnable {

    private RedisService redisService;


    public TaskWatchThread(RedisService redisService){
        this.redisService = redisService;
    }


    @Override
    public void run() {

        while (true){
            try {
                System.out.println("任务监控线程执行中...");
                ConcurrentHashMap.KeySetView<String, Long> keys = TaskRecord.taskRecordMap.keySet();
                for(String key:keys){

                    Long value = TaskRecord.taskRecordMap.get(key);
                    System.out.println(String.format("任务号：%s 上次被获取到的时间为：%s",key,value));
                    Long currentTime = System.currentTimeMillis();

                    if((currentTime - value) > 30*60*1000){
                        System.out.println("执行超时的任务为："  + key);
                        //大于半个小时，说明任务超时了
                        this.redisService.lpush("unicrawler:tasks:all",key);
                        TaskRecord.taskRecordMap.remove(key);
                    }
                }
                Thread.sleep(30*1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
